import { _decorator, BoxCollider2D, CCInteger, Component, ICollisionEvent, Node, Vec3, PhysicsSystem2D, 
    Collider2D, Contact2DType, RigidBody2D, Vec2, UITransform, IPhysics2DContact, input, Input } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('move')
export class move extends Component {


    /**
     * using aabb (axis-aligned bounding box) is more efficient, but not that accurate.
     * aabb is create a rectangle collider box and each sides are parallel to axis.
     * !!! so the collider box won't rotate with object. !!!
     * 2D:
     *      for each collider box, we only need 2 vectors: min, max
     *      min - left bottom point of object
     *      max - right top point of object
     *      
     *      same idea with Rect.intersects().
     *      1. A-y-min > B-y-max
     *      2. A-x-min > B-x-max
     *      3. B-y-min > A-y-max
     *      4. B-x-min > A-x-max
     * 
     * 3D:
     *      CCAABB
     *      from 8 vertices object A and object B
     *      choose 2 max and 2 min. compare.
     */

    @property(CCInteger)
    direction1: number = 1;

    private direction = { x: 0, y: 0 };

    @property(CCInteger)
    speed: number = 0;

    private position = new Vec3();
    private rigid: RigidBody2D = null;
    //private gravity: number = 0;
    private ifAcc: boolean = true;

    start() {
        this.direction.x = this.direction1;
        this.direction.y = this.direction1;
        this.position = this.node.getPosition();
        let collider = this.node.getComponent(Collider2D);
        this.collisionEvent(collider);
        this.rigid = this.node.getComponent(RigidBody2D);
        //input.on(Input.EventType.TOUCH_START, )
        //this.gravity = 0;
    }

    collisionEvent(collider: Collider2D) {
        collider.on(Contact2DType.BEGIN_CONTACT, this.onCollisionEnter, this);
        collider.on(Contact2DType.END_CONTACT, this.onCollisionExit, this);
    }

    onCollisionEnter(selfCollider: Collider2D, otherCollider: Collider2D, contact: IPhysics2DContact){
        const otherNode = otherCollider.node.name;

        if (otherNode == 'Object2' || otherNode == 'Object1') {
            this.direction.x *= -1;
            this.direction.y *= -1;
            this.ifAcc = false;
        } else if (otherNode == 'left' || otherNode == 'right') {
            this.direction.x *= -1;
            this.ifAcc = false;
        } else if (otherNode == 'ceil' || otherNode == 'ground') {
            this.direction.y *= -1;
            this.ifAcc = false;
        }
        
        //this.gravity = 3;


    }

    onCollisionExit(event: ICollisionEvent){
    }

    update(deltaTime: number) {
        if (this.ifAcc) this.speed += 0.05;
        //console.log(this.node.position);
        this.node.setPosition(new Vec3(this.position.x+this.speed*this.direction.x, this.position.y+this.speed*this.direction.y, 0));
        this.position = this.node.getPosition();
        
    }
}
